import GameData from "../../../Game/info/GameData";
import { GamePropType, PlayerID } from "../../../Game/info/GameEnum";
import { Global } from "../../../Game/info/Global";
import MusicManager from "../../../MusicManager";
import Scene from "../../../Scene";
import { SceneState, TButton, TLayout } from "../../../SceneControl";
import Utils from "../../../Utils";
import ChooseScene from "./ChooseScene";

const { ccclass, property } = cc._decorator;

@ccclass
export default class StartGameScene extends Scene {

    @property(cc.Node)
    choosePanel: cc.Node = null;

    @property(cc.JsonAsset)
    nikeNames: cc.JsonAsset = null;

    @property([cc.SpriteFrame])
    propIcon: cc.SpriteFrame[] = [];

    @property([cc.SpriteFrame])
    roleIcon: cc.SpriteFrame[] = [];

    useGameData: GameData;

    protected onEnable(): void {
        super.onEnable();
        this.initScene();

        let useGameData = new GameData(Global.gameInfo.roleId);
        this.useGameData = useGameData;

        let typeList = [PlayerID.player1, PlayerID.player2, PlayerID.player3, PlayerID.player4, PlayerID.player5, PlayerID.player6];
        let nameArr: string[] = this.nikeNames.json;
        let typeIndex = [
            [0, 1, 2],
            [3, 4],
            [5, 6],
            [7, 8],
            [9, 10],
            [11, 12]
        ];

        typeList.forEach(type => {
            let nikeNameIndex = Utils.getRandom(0, nameArr.length - 1);
            let props: GamePropType[] = [];
            props.length = 18;
            props.fill(0);
            useGameData.enemy.push({ roleId: Utils.getRandomChoose(typeIndex[type]), nikeName: nameArr[nikeNameIndex], props: props, hide: false });
            nameArr.splice(nikeNameIndex, 1);
        })


        let list = cc.find("选择道具/list", this.node);
        list.children.forEach((item, index) => {
            let temp = index * 3;
            item.getChildByName("红点").active = Global.gameInfo.propCount[temp] > 0 || Global.gameInfo.propCount[temp + 1] > 0 || Global.gameInfo.propCount[temp + 2] > 0;
        });

    }

    public initScene() {
        let upLayout = new TLayout("up");
        let downLayout = new TLayout("down");
        let upList = cc.find("选择道具/list", this.node);

        upLayout.buttonList = [
            [new TButton(upList.children[0]), new TButton(upList.children[1]), new TButton(upList.children[2])],
            [new TButton(upList.children[3]), new TButton(upList.children[4]), new TButton(upList.children[5])],
        ]

        downLayout.buttonList = [
            [new TButton(cc.find("选择道具/选好了", this.node))]
        ]

        this.tscene.addLayout(upLayout);
        this.tscene.addLayout(downLayout, { row: 1, line: 0 });
        this.tscene.site = { row: 1, line: 0 };
        this.tscene.onBack = () => {
            this.node.destroy();
        }
        this.tscene.joinController();
    }

    openChosePanel(event, customEventData) {
        MusicManager.instance.play(MusicManager.instance.btnMove);
        this.choosePanel.getComponent(ChooseScene).reset(event.target, parseInt(customEventData));
        this.choosePanel.active = true;
    }

    onChoseChange(index: number) {
        let type = Math.floor(index / 3);
        let slot = cc.find("选择道具/list", this.node).children[type];
        let iconSprite = slot.getChildByName("icon").getComponent(cc.Sprite);
        if (iconSprite.spriteFrame) {
            if (iconSprite.spriteFrame == this.propIcon[index]) {
                this.useGameData.self.props[index] = 0;
            } else {
                this.useGameData.self.props[type * 3 + 1] = 0;
                this.useGameData.self.props[type * 3 + 2] = 0;
                this.useGameData.self.props[type * 3 + 3] = 0;
                iconSprite.spriteFrame = null;
                return this.onChoseChange(index);
            }
            iconSprite.spriteFrame = null;
            slot.getChildByName("propName").getComponent(cc.Label).string = "";
        } else {
            iconSprite.spriteFrame = this.propIcon[index];
            this.useGameData.self.props[index] = 1;
            slot.getChildByName("propName").getComponent(cc.Label).string = Global.PropInfo[index].名字;
        }
    }

    startMatching() {
        MusicManager.instance.play(MusicManager.instance.btnMove);
        cc.director.preloadScene("Game");
        this.node.getChildByName("选择道具").active = false;
        this.node.getChildByName("开始匹配").active = true;

        this.tscene.currLayout.buttonList = [
            [new TButton(this.node)]
        ]
        this.tscene.sceneState = SceneState.stop;
        this.tscene.apply();

        let circle = cc.find("开始匹配/bg/circle_large", this.node)
        cc.tween(circle)
            .to(2, { angle: 360 })
            .set({ angle: 0 })
            .union()
            .repeatForever()
            .start();

        this.addEnemyProp();

        let maxWaitTime = 0;
        if (Global.chooseMode == 0) {
            maxWaitTime = this.startMatch6();
        } else {
            maxWaitTime = this.startMatch1V1();
        }

        this.scheduleOnce(() => {
            Global.currentGameData = this.useGameData;
            for (let i = 0; i < Global.currentGameData.self.props.length; i++) {
                if (Global.currentGameData.self.props[i]) {
                    Global.gameInfo.propCount[i]--;
                }
            }
            Global.saveGameInfo();
            cc.director.loadScene("Game");
        }, maxWaitTime + 0.5)
    }

    startMatch1V1(): number {
        let show = cc.find("开始匹配/show", this.node)
        let selfType = Global.getPlayerId(this.useGameData.self.roleId);
        let maxWaitTime = Utils.getRandom(10, 50) / 10;
        let nodes = show.children.concat();
        let selfNode = nodes.splice(selfType, 1)[0];
        let randomEnemy = Utils.getRandomChoose(nodes);
        let randomEnemyType = show.children.findIndex(item => item == randomEnemy);
        show.children.forEach(item => item != selfNode && (item.active = false));
        selfNode.position = cc.v3(0, 0);

        let playerIconNode = selfNode.getChildByName("player");
        playerIconNode.active = true;

        selfNode.getChildByName("name").getComponent(cc.Label).string = "自己";
        selfNode.getChildByName("orange").active = true;
        playerIconNode.getComponent(cc.Sprite).spriteFrame = this.roleIcon[this.useGameData.self.roleId];
        selfNode.getChildByName("selfTip").active = true;

        cc.tween(playerIconNode)
            .set({ scale: 0 })
            .to(0.3, { scale: 1 }, { easing: 'elasticOut' })
            .start();

        this.scheduleOnce(() => {
            randomEnemy.active = true;
            playerIconNode = randomEnemy.getChildByName("player");
            playerIconNode.active = true;
            cc.tween(playerIconNode)
                .set({ scale: 0 })
                .to(0.3, { scale: 1 }, { easing: 'elasticOut' })
                .start();
            randomEnemy.getChildByName("name").getComponent(cc.Label).string = this.useGameData.enemy[randomEnemyType].nikeName;
            randomEnemy.getChildByName("orange").active = true;
            playerIconNode.getComponent(cc.Sprite).spriteFrame = this.roleIcon[this.useGameData.enemy[randomEnemyType].roleId];
            randomEnemy.getChildByName("selfTip").active = false;

            for (let i = 0; i < this.useGameData.enemy.length; i++) {
                if (!(i == randomEnemyType || i == selfType)) {
                    this.useGameData.enemy[i].hide = true;
                }
            }
        }, maxWaitTime);

        return maxWaitTime;
    }

    startMatch6(): number {
        let show = cc.find("开始匹配/show", this.node)
        let nodes = show.children.concat();
        this.propIcon[this.useGameData.self.roleId]
        let selfType = Global.getPlayerId(this.useGameData.self.roleId);
        let maxWaitTime = 0;
        for (let i = 0; i < nodes.length; i++) {
            let node = nodes[i];
            let waitTime = i == selfType ? 0.5 : Utils.getRandom(10, 50) / 10;
            waitTime > maxWaitTime && (maxWaitTime = waitTime);
            this.scheduleOnce(() => {
                node.getChildByName("orange").active = true;
                let playerIconNode = node.getChildByName("player");
                playerIconNode.active = true;
                cc.tween(playerIconNode)
                    .set({ scale: 0 })
                    .to(0.3, { scale: 1 }, { easing: 'elasticOut' })
                    .start();
                if (i == selfType) {
                    node.getChildByName("name").getComponent(cc.Label).string = "自己";
                    playerIconNode.getComponent(cc.Sprite).spriteFrame = this.roleIcon[this.useGameData.self.roleId];
                    node.getChildByName("selfTip").active = true;
                } else {
                    node.getChildByName("name").getComponent(cc.Label).string = this.useGameData.enemy[i].nikeName;
                    playerIconNode.getComponent(cc.Sprite).spriteFrame = this.roleIcon[this.useGameData.enemy[i].roleId];
                    node.getChildByName("selfTip").active = false;
                }
            }, waitTime)
        }
        return maxWaitTime;
    }

    addEnemyProp() {
        let selfPropTime = this.useGameData.self.props.filter(value => value === 1).length;
        let probability = cc.v2(0, 0.05).lerp(cc.v2(6, 0.5), selfPropTime / 6).y;
        if (Global.chooseMode == 1) {
            probability *= 1.2;
        }
        this.useGameData.enemy.forEach(enemy => {
            for (let i = 0; i < 6; i++) {
                B: for (let j = 0; j < 3; j++) {
                    if (Utils.getRandomBoolean(probability)) {
                        enemy.props[i * 3 + j] = 1;
                        break B;
                    }
                }
            }
        })
    }

    showTip() {
        let inforTip = this.node.getChildByName("inforTip");
        inforTip.active = true;
        cc.tween(inforTip)
            .delay(1)
            .set({ active: false })
            .start();
    }
}
